/*
 * Copyright (c) 2016 Breezee.org. All Rights Reserved. 
 */
'use strict';
const request = require('request');
const extend = require('extend');
const uuid = require('uuid');
const api = require('../utils/api');

/**
 * 工具类
 * @type {{send: module.exports.send, dateFormatter: module.exports.dateFormatter, padZero: module.exports.padZero}}
 */
module.exports = {

    /**
     * 发送请求
     * @param param 请求的参数
     * @param callback 回调方法
     */
    send: function (param, callback) {
        if (global.config.mockFlag) {
            //TODO: mock框架的优化
        } else {
            let defaultParam = {
                json: {},
                headers: {
                    "Content-Type": "application/json",
                    "Accept": "application/json",
                    "Accept-Language": param.language || "zh"
                }
            };
            let _param = extend(true, {}, defaultParam, param);
            request(_param, callback);
        }
    },

    /**
     * 深度合并对象
     * @param defaultParam
     * @param myParam
     */
    extend: function (defaultParam, myParam) {
        return extend(true, {}, defaultParam, myParam);
    },

    /**
     * 日期格式化
     * @param date 日期
     * @param format 格式
     * @returns {*} 格式化后的字符串值
     */
    dateFormatter: function (date, format) {
        let o = {
            "M+": date.getMonth() + 1, //month
            "d+": date.getDate(),      //day
            "h+": date.getHours(),     //hour
            "m+": date.getMinutes(),   //minute
            "s+": date.getSeconds(),   //second
            "w+": "天一二三四五六".charAt(date.getDay()),   //week
            "q+": Math.floor((date.getMonth() + 3) / 3),  //quarter
            "S": date.getMilliseconds() //millisecond
        };
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1,
                (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (let k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1,
                    RegExp.$1.length == 1 ? o[k] :
                        ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    },
    string2date : function(string, format){
        format = format || 'yyyy-MM-dd';
        let y = string.substring(format.indexOf('y'),format.lastIndexOf('y')+1);//年
        let M = string.substring(format.indexOf('M'),format.lastIndexOf('M')+1);//月
        let d = string.substring(format.indexOf('d'),format.lastIndexOf('d')+1);//日
        let h = string.substring(format.indexOf('h'),format.lastIndexOf('h')+1);//时
        let m = string.substring(format.indexOf('m'),format.lastIndexOf('m')+1);//分
        let s = string.substring(format.indexOf('s'),format.lastIndexOf('s')+1);//秒

        if(s == null ||s == "" || isNaN(s)) {s = new Date().getSeconds();}
        if(m == null ||m == "" || isNaN(m)) {m = new Date().getMinutes();}
        if(h == null ||h == "" || isNaN(h)) {h = new Date().getHours();}
        if(d == null ||d == "" || isNaN(d)) {d = new Date().getDate();}
        if(M == null ||M == "" || isNaN(M)) {M = new Date().getMonth()+1;}
        if(y == null ||y == "" || isNaN(y)) {y = new Date().getFullYear();}
        let dt = null ;
        eval ("dt = new Date('"+ y+"', '"+(M-1)+"','"+ d+"','"+ h+"','"+ m+"','"+ s +"')");
        return dt;
    },

    /**
     * 在指定字符前面补0，以达到指定的长度
     * @param str 需要补0的字符串
     * @param length 需要达到的长度
     * @returns {string} 补0后的字符串
     */
    padZero: function (str, length) {
        let newStr = str + "";
        while (newStr.length < length) {
            newStr = "0" + newStr;
        }
        return newStr;
    },

    /**
     * 获取请求端的类型
     * @param str
     * @returns {string}
     */
    endType: function (str) {
        return /Mobile/.test(str) ? "mobile" : "desktop";
    },

    endTypeEnum: {
        desktop: 1,
        mobile: 3,
        pad: 5
    },

    /**
     * 获取随机串
     */
    uuid: function () {
        return uuid.v4();
    },

    getUserInfo: function (code, callback) {
        global.tool.send({
            method: 'post',
            uri: api.get('8f7def63cc5845468b2c65a69abb0664'),
            json: {
                properties: {
                    weChat: code
                }
            }
        }, function (error, response, body) {
            console.log("-------------callback body start-------------");
            console.log(body);
            console.log("-------------callback body end-------------");
            if (body && body.rows.length > 0)
                callback(body.rows[0]);
            else
                callback({status: 0});
        });
    },

    getLangText: function (string, lang) {
        lang = lang || "en";
        lang = lang.substr(0, 2);
        try {
            let ret = [], tmp = string.split("|"), obj;
            for (let i = 0; i < tmp.length; i++) {
                if (tmp[i].indexOf('{') > -1) {
                    obj = JSON.parse(tmp[i]);
                    ret.push(obj[lang] || obj['en'] || "No" + lang + " Config");
                } else {
                    ret.push(tmp[i]);
                }
            }
            return ret.join(',');
        } catch (e) {

        }
        return string;
    },


    getEnumByCode : function(code){
        return new Promise(function(resolve , reject){
            global.tool.send({
                method: 'GET',
                uri: api.get('5b8e27d5bb9547f48235bd70aea199b9').replace('{code}', code),
            }, function (error, response, body) {
                if (body && body.rows.length > 0){
                    resolve(body.rows);
                }else{
                    reject([]);
                }
            });
        });
    },

    getEnumsByCodes : function(codeArray){
        var promiseArray = [];
        for(var code of codeArray){
            promiseArray.push(global.tool.getEnumByCode(code));
        }
        return promiseArray;
    },





};